﻿using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FCDB.WEB.Helpers
{
    public class TimeHttpModule : IHttpModule
    {
        private DateTime starttime;
        private static Logger logger = NLog.LogManager.GetCurrentClassLogger();
        public void Dispose()
        {
             
        }

        public void Init(HttpApplication application)
        {

            application.BeginRequest += new EventHandler(application_BeginRequest);
            application.EndRequest += new EventHandler(application_EndRequest);
        }
        private void application_BeginRequest(object sender, EventArgs e)
        {
            //object sender是BeginRequest传递过来的对象
            //里面存储的就是HttpApplication实例
            //HttpApplication实例里包含HttpContext属性
            starttime = DateTime.Now;
        }

        private void application_EndRequest(object sender, EventArgs e)
        {
            DateTime endtime = DateTime.Now;
            HttpApplication application = (HttpApplication)sender;
            HttpContext context = application.Context;
            var ms = (endtime - starttime).Milliseconds;
            String url = HttpContext.Current.Request.Url.ToString();
            String logStr = "";
            if(ms>3000)
            {
                logStr = String.Format("请求时间：{0}ms===高危====超过3秒以上url：{1}", ms.ToString(), url);
            }else if(ms>1000) 
            {
                logStr = String.Format("请求时间：{0}ms===危险====超过1秒以上url：{1}", ms.ToString(), url);
             }else
            {
                logStr = String.Format("请求时间：{0}ms===正常=====超过1秒以下url：{1}", ms.ToString(), url);
            }
            logger.Info(logStr);
        }
 

    }
}